package com.rabbiter.ordering.service;



import com.rabbiter.ordering.entity.Package;
import com.rabbiter.ordering.entity.PackageFood;
import com.rabbiter.ordering.mapper.PackageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PackageService {

    @Autowired
    private PackageMapper packageMapper;

    public List<Package> list() {
        List<Package> packages = packageMapper.selectAll();
        packages.forEach(pkg -> {
            List<PackageFood> foods = packageMapper.selectFoodsByPackageId(pkg.getId());
            pkg.setFoods(foods);
        });
        return packages;
    }

    public Package getById(Integer id) {
        Package pkg = packageMapper.selectById(id);
        if (pkg != null) {
            List<PackageFood> foods = packageMapper.selectFoodsByPackageId(pkg.getId());
            pkg.setFoods(foods);
        }
        return pkg;
    }

    public void saveOrUpdate(Package pkg) {
        if (pkg.getId() == null) {
            packageMapper.insert(pkg);
        } else {
            packageMapper.update(pkg);
            packageMapper.deletePackageFoods(pkg.getId());
        }

        // 保存套餐包含的菜品
        if (pkg.getFoods() != null && !pkg.getFoods().isEmpty()) {
            pkg.getFoods().forEach(food -> {
                food.setPackageId(pkg.getId());
                packageMapper.insertPackageFood(food);
            });
        }
    }

    public void delete(Integer id) {
        packageMapper.deletePackageFoods(id);
        packageMapper.delete(id);
    }
}
